#include "elog_uart.h"
#include "stdint.h"
#include "stdarg.h"
#include "string.h"

/* drivers #include */
#include "rtconfig.h"

/* device #include  */
#include "device.h"
#include "serial.h"

/* clib #include */
#include "stdio.h"

static rt_device_t console;

__attribute__((weak)) void hw_console_output(char *str)
{
    // HAL_UART_Transmit(&huart4, (uint8_t *)str, strlen(str), 1000u)
}

int rt_console_set_device(char *name)
{
    int ret = RT_EOK;
    struct serial_configure config = {0};
    
    if (RT_NULL == name)
    {
        ret = -RT_ERROR;
        goto __exit;
    }

    console = rt_device_find(name);
    if (RT_NULL == console)
    {
        ret = -RT_ERROR;
        goto __exit;
    }
    
    config.baud_rate = CONSOLE_BAUD_RATE;   
    config.bufsz = 512;
    rt_device_control(console, RT_DEVICE_CTRL_CONFIG, (void *)&config);
    rt_device_open(console, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_STREAM);
__exit:
    return ret;
}

int kprintf(const char *fmt, ...)
{
    va_list args;
    uint32_t length = 0;
    char log_buf[CONSOLEBUF_SIZE + 1] = {0};

    memset(log_buf, 0, sizeof(log_buf));
    va_start(args, fmt);
    /* the return value of vsnprintf is the number of bytes that would be
     * written to buffer had if the size of the buffer been sufficiently
     * large excluding the terminating null byte. If the output string
     * would be larger than the rt_log_buf, we have to adjust the output
     * length. */
    length = vsnprintf(log_buf, sizeof(log_buf) - 1, fmt, args);
    if (length > CONSOLEBUF_SIZE - 1)
    {
        length = CONSOLEBUF_SIZE - 1;
    }

#ifdef RT_USING_DEVICE
    if (RT_NULL != console)
        rt_device_write(console, 0, log_buf, length);
#else
    hw_console_output(log_buf);
#endif /* RT_USING_DEVICE */
    va_end(args);

    return length;
}
